package com.opal.reporforms.service.impl;

import com.opal.domain.ReturnMessageData;
import com.opal.model.DataGridData;
import com.opal.reporforms.entity.*;
import com.opal.reporforms.mapper.oracle.ThreeBomMapper;
import com.opal.reporforms.service.ThreeBomService;
import com.opal.utils.DataGridUtils;
import com.opal.utils.ExcelDownloadUtil;
import com.opal.utils.SheetStyle;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ThreeBomServiceImpl implements ThreeBomService {
    private List<ThreeForm> threeForms = new ArrayList<>();
    private List<TwoForm> twoForms = new ArrayList<>();
    private List<OneForm> oneForms = new ArrayList<>();
    private String pkorg;  //组织
    private String code;   //物料编码
    //private DataGrid rmd; //分页
    @Autowired
    private ThreeBomMapper threeBomMapper;

    @Override
    public ReturnMessageData getPkFactoryService() {
        ReturnMessageData returnMessageData;
        List<OrgFactory> pkFactory = threeBomMapper.getPkFactory();
        returnMessageData = new ReturnMessageData(200, "成功", pkFactory);
        return returnMessageData;
    }

    @Override
    public ReturnMessageData getBdMaterialByCodeService(String code) {
        ReturnMessageData returnMessageData;
        List<BdMaterial> result = threeBomMapper.getBdMaterialByCode(code.trim());
        if (result.size() > 0) {
            returnMessageData = new ReturnMessageData(200, "成功", result.get(0));
        } else {
            returnMessageData = new ReturnMessageData(500, "未查询到物料编码");
        }
        return returnMessageData;
    }

    @Override
    public DataGridData selectOneFormService(String pkorg, String code, DataGridData rmd) {
        getPkOrgAanCode(pkorg, code);
       // this.rmd = rmd;
        //处理分页
        DataGridUtils.processingPageData(rmd);
        int total = threeBomMapper.countOneForm(pkorg, code, rmd);
        if (total > 0) {
            List<OneForm> oneForms = threeBomMapper.selectOneFormPage(pkorg, code, rmd);
            this.oneForms = oneForms;
            rmd = new DataGridData(200, "获取成功");
            rmd.setRows(oneForms);
            rmd.setTotal(total);
        } else {
            rmd = new DataGridData(200, "未查询到相关的信息");
        }
        return rmd;
    }

    @Override
    public DataGridData selectOneFormService(String pkorg, String code) {
        DataGridData dataGrid;
        List<OneForm> oneForms = threeBomMapper.selectOneForm(pkorg, code);
        if (oneForms.size() > 0) {
            this.oneForms = oneForms;
            dataGrid = new DataGridData(200, "获取成功");
            dataGrid.setRows(oneForms);
        } else {
            dataGrid = new DataGridData(200, "未查询到相关的信息");
        }
        return dataGrid;
    }

    @Override
    public DataGridData selectTwoFormService(String pkorg, String code) {
        getPkOrgAanCode(pkorg, code);
        DataGridData dataGrid;
        List<TwoForm> twoForms = threeBomMapper.selectTwoForm(pkorg, code);
        if (twoForms.size() > 0) {
            this.twoForms = twoForms;
            dataGrid = new DataGridData(200, "获取成功");
            dataGrid.setRows(twoForms);
        } else {
            dataGrid = new DataGridData(200, "未查询到相关的信息");
        }
        return dataGrid;
    }

    @Override
    public DataGridData selectThreeFormService(String pkorg, String code) {
        getPkOrgAanCode(pkorg, code);
        DataGridData dataGrid;
        List<ThreeForm> threeForms = threeBomMapper.selectThreeForm(pkorg, code);
        if (threeForms.size() > 0) {
            this.threeForms = threeForms;
            dataGrid = new DataGridData(200, "获取成功");
            dataGrid.setRows(threeForms);
        } else {
            dataGrid = new DataGridData(200, "未查询到相关的信息");
        }
        return dataGrid;
    }

    @Override
    public ReturnMessageData printBomService(String[] BOMs, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (BOMs.length == 1) {
                switch (BOMs[0]) {
                    case "第一联":
                        HSSFWorkbook h1 = this.getHSSFWorkbook("static/templates/bom/N321001562-1.xls");
                        pringOneBOM(this.oneForms,h1);
                        ExcelDownloadUtil.responseData(response, h1);
                        break;
                    case "第二联":
                        HSSFWorkbook h2 = this.getHSSFWorkbook("static/templates/bom/N321001562-2.xls");
                        pringTwoBOM(this.twoForms,h2);
                        ExcelDownloadUtil.responseData(response, h2);
                        break;
                    case "第三联":
                        HSSFWorkbook h3 = this.getHSSFWorkbook("static/templates/bom/N321001562-3.xls");
                        //查询数据
                        this.pringThreeBOM(this.threeForms,h3);
                        ExcelDownloadUtil.responseData(response, h3);
                        break;
                }

            } else {
                HSSFWorkbook h = getHSSFWorkbook("static/templates/bom/N321001562.xls");
                //循环获取要导出的Excel
                for (String b : BOMs) {
                    if ("第一联".equals(b)) {
                        //查询数据
                        pringOneBOM(this.oneForms,h);
                    }
                    if ("第二联".equals(b)) {
                        //查询数据
                        this.pringTwoBOM(this.twoForms, h);
                    }
                    if ("第三联".equals(b)) {
                        //查询数据
                        this.pringThreeBOM(this.threeForms,h);
                    }
                }
                ExcelDownloadUtil.responseData(response, h);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new ReturnMessageData(500, "导出失败");
        } catch (IOException e) {
            e.printStackTrace();
            return new ReturnMessageData(500, "导出失败");
        }
        return new ReturnMessageData(500, "导出成功，若没有提示请查看浏览器中设置-》下载");
    }

    private void pringOneBOM(List<OneForm> oneForms,HSSFWorkbook h) throws IOException {
        //页面sheel
        HSSFSheet sheet = h.getSheet("第一联");
        //设置表头内容
        HSSFRow row = sheet.getRow(1);  //第二行
        HSSFCell proCodeCell = row.getCell(3);//物料编码
        HSSFCell currentDateCell = row.getCell(8);//打印日期
        proCodeCell.setCellValue(oneForms.get(0).getProCode());
        currentDateCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        row = sheet.getRow(2);  //第三行
        HSSFCell proNameCell = row.getCell(3); //物料名称
        proNameCell.setCellValue(oneForms.get(0).getProName());

        row = sheet.getRow(3);  //第四行
        HSSFCell isPorduceCell = row.getCell(3); //是否可生产
        HSSFCell hversionCell = row.getCell(5); //BoM版本号
        HSSFCell formulaNaCell = row.getCell(8); //配方号
        isPorduceCell.setCellValue(oneForms.get(0).getIsProduce());
        hversionCell.setCellValue(oneForms.get(0).getHversion());
        formulaNaCell.setCellValue(oneForms.get(0).getFormulaNo());

        for (int i = 0; i < oneForms.size() - 1; i++) {
            row = sheet.getRow(i + 5);
            row.setHeight((short) (30 * 20));
            HSSFCell cell = row.createCell(1);//行号
            cell.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            cell.setCellValue(oneForms.get(i).getRowno());
            cell = row.createCell(2);//相别
            cell.setCellStyle(getBorderStyle(h));
            cell.setCellValue(oneForms.get(i).getXbName());
            cell = row.createCell(3);//物料编码
            cell.setCellStyle(getBorderStyle(h));
            cell.setCellValue(oneForms.get(i).getMaterialCode());
            cell = row.createCell(4);//物料名称
            cell.setCellValue(oneForms.get(i).getMaterialName());
            cell.setCellStyle(getBorderStyle(h));
            cell = row.createCell(5);  //只设置样式
            cell.setCellStyle(getBorderStyle(h));
            cell = row.createCell(6); //单位
            cell.setCellStyle(getBorderStyle(h));
            cell.setCellValue(oneForms.get(i).getMeasdocName());
            cell = row.createCell(7);//标准用量
            cell.setCellStyle(getBorderStyle(h));
            cell.setCellValue(oneForms.get(i).getStandardDosage());
            cell = row.createCell(8); //底数
            cell.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            cell.setCellValue(oneForms.get(i).getDividend());
            cell = row.createCell(9); //备注
            cell.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            cell.setCellValue(oneForms.get(i).getVnote());
        }
    }

    private void pringTwoBOM(List<TwoForm> twoForms,HSSFWorkbook h2) {
        //页面sheel
        HSSFSheet sheet = h2.getSheet("第二联");
        //设置表头内容
        HSSFRow row = sheet.getRow(1);  //第二行
        HSSFCell materialCodeCell = row.getCell(2);//物料编码
        HSSFCell currentDateCell = row.getCell(5);//打印日期
        materialCodeCell.setCellValue(twoForms.get(0).getMaterialCode());
        currentDateCell.setCellValue("打印日期:" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        row = sheet.getRow(2);//第三行
        HSSFCell materialNameCell = row.getCell(2);//物料名称
        materialNameCell.setCellValue(twoForms.get(0).getMaterialName());

        row = sheet.getRow(3);//第四行
        HSSFCell isPorduceCell = row.getCell(2); //是否可生产
        HSSFCell version = row.getCell(3); //工艺版本号
        HSSFCell b = row.getCell(5); //配方号
        isPorduceCell.setCellValue(twoForms.get(0).getIsProduce());
        version.setCellValue("工艺版本号:" + twoForms.get(0).getVersion());
        b.setCellValue("配方号:" + twoForms.get(0).getFormulaNo());
        int j = 0;
        for (int i = 0; i < twoForms.size() - 1; i++) {
            HSSFRow row1;
            if (i == 0) {
                row = sheet.createRow(5);//第六行.....
                row.setHeight((short) (80 * 20));
                row1 = sheet.createRow(6);//第7行
                row1.setHeight((short) (50 * 20));
                //处理合并单元格
                mergeCells(sheet, 5);
            } else {
                j += 2;
                row = sheet.createRow(5 + j);//第六行.....
                row.setHeight((short) (80 * 20));
                row1 = sheet.createRow(6 + j);//第7行
                row1.setHeight((short) (50 * 20));
                //处理合并单元格
                mergeCells(sheet, 5 + j);
            }

            HSSFCell vprocessno = row.createCell(1);//Step步骤
            vprocessno.setCellValue(twoForms.get(i).getVprocessno());
            vprocessno.setCellStyle(getBorderStyle(h2));

            HSSFCell vcraftnote = row.createCell(2);//操作说明
            vcraftnote.setCellValue(twoForms.get(i).getVcraftnote());
            vcraftnote.setCellStyle(getBorderStyle(h2));

            HSSFCell note = row.createCell(4); //Record记录
            note.setCellValue(twoForms.get(i).getNote());
            note.setCellStyle(getBorderStyle(h2));

            HSSFCell materialInfo = row1.createCell(2);//操作说明下行
            materialInfo.setCellValue(twoForms.get(i).getMaterialInfo());
            materialInfo.setCellStyle(getBorderStyle(h2));

        }
    }

    private void pringThreeBOM(List<ThreeForm> threeForm,HSSFWorkbook h) {
        //页面sheel
        HSSFSheet sheet = h.getSheet("第三联");
        //设置表头内容
        HSSFRow row = sheet.getRow(1);  //第二行
        HSSFCell materialCodeCell = row.getCell(2);//物料编码
        HSSFCell currentDateCell = row.getCell(6);//打印日期
        materialCodeCell.setCellValue(threeForm.get(0).getProCode()) ;
        currentDateCell.setCellValue("打印日期:" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        row = sheet.getRow(2);//第三行
        HSSFCell materialNameCell = row.getCell(2);//物料名称
        materialNameCell.setCellValue(threeForm.get(0).getProName());

        row = sheet.getRow(3);//第四行
        HSSFCell isPorduceCell = row.getCell(2); //是否可生产
        HSSFCell version = row.getCell(4); //工艺版本号
        HSSFCell formulaNo = row.getCell(6); //配方号
        isPorduceCell.setCellValue(threeForm.get(0).getIsProduce());
        version.setCellValue("工艺版本号:" + threeForm.get(0).getVersion());
        formulaNo.setCellValue("配方号:" + threeForm.get(0).getFormulaNo());

        row = sheet.getRow(4);//第五行
        HSSFCell proExecuteNo = row.getCell(2); //执行标准
        HSSFCell vdef8 = row.getCell(5); // 执行标准类型
        proExecuteNo.setCellValue(threeForm.get(0).getProExecuteNo());
        vdef8.setCellValue("执行标准类型:" + threeForm.get(0).getVdef8());

        //循环内容
        for (int i = 0; i < threeForm.size() - 1; i++) {
            row = sheet.createRow(6 + i);//第7行开始...
            row.setHeight((short) (50 * 20));
            HSSFCell vdef12 = row.createCell(1); //检验项目类型
            vdef12.setCellStyle(getBorderStyle(h));
            HSSFCell vdef13 = row.createCell(2); // 检验项目描述
            vdef13.setCellStyle(getBorderStyle(h));
            HSSFCell vdef14 = row.createCell(3); // 检验方法
            vdef14.setCellStyle(getBorderStyle(h));
            HSSFCell vdef15 = row.createCell(4); // 指标(内控)
            vdef15.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            HSSFCell vdef15_2 = row.createCell(5); // 指标(外控)
            vdef15_2.setCellStyle(getBorderStyle(h));
            HSSFCell vdef16 = row.createCell(6); // 检验周期
            vdef16.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            HSSFCell a = row.createCell(7); // 检验结果
            a.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            HSSFCell b = row.createCell(8); // By
            b.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            //设置值
            vdef12.setCellValue(threeForm.get(i).getVdef12());
            vdef13.setCellValue(threeForm.get(i).getVdef13());
            vdef14.setCellValue(threeForm.get(i).getVdef14());
            vdef15.setCellValue(threeForm.get(i).getVdef15());
            vdef15_2.setCellValue(threeForm.get(i).getVdef15_2());
            vdef16.setCellValue(threeForm.get(i).getVdef16());
            //处理结尾备注
            if (threeForm.size() - 2 == i) {
                row = sheet.createRow(6 + i + 1);
                row.setHeight((short) (100 * 20));
                //合并单元格
                CellRangeAddress cra = new CellRangeAddress(6 + i + 1, 6 + i + 1, 1, 8);
                sheet.addMergedRegion(cra);
                SheetStyle.mergerCellsStyle(sheet, cra);
                HSSFCell vnote = row.createCell(1);
                vnote.setCellValue(threeForm.get(i).getVnote());
                vnote.setCellStyle(SheetStyle.getDefaultCellStyle(h));
            }

        }
    }

    //第二联合并单元格
    private void mergeCells(HSSFSheet sheet, int i) {

        CellRangeAddress cra = new CellRangeAddress(i, i + 1, 1, 1);
        CellRangeAddress cra2 = new CellRangeAddress(i, i, 2, 3);
        CellRangeAddress cra3 = new CellRangeAddress(i + 1, i + 1, 2, 3);
        CellRangeAddress cra4 = new CellRangeAddress(i, i + 1, 4, 5);
        CellRangeAddress cra5 = new CellRangeAddress(i, i + 1, 6, 6);
        CellRangeAddress cra6 = new CellRangeAddress(i, i + 1, 7, 7);
        sheet.addMergedRegion(cra);
        sheet.addMergedRegion(cra2);
        sheet.addMergedRegion(cra3);
        sheet.addMergedRegion(cra4);
        sheet.addMergedRegion(cra5);
        sheet.addMergedRegion(cra6);

        // 使用RegionUtil类为合并后的单元格添加边框
        SheetStyle.mergerCellsStyle(sheet, cra);
        SheetStyle.mergerCellsStyle(sheet, cra2);
        SheetStyle.mergerCellsStyle(sheet, cra3);
        SheetStyle.mergerCellsStyle(sheet, cra4);
        SheetStyle.mergerCellsStyle(sheet, cra5);
        SheetStyle.mergerCellsStyle(sheet, cra6);
    }

    //创建主对象
    private HSSFWorkbook getHSSFWorkbook(String thempatePath) throws IOException {
        // String path = ThreeBomServiceImpl.class.getClassLoader().getResource("static/templates/bom/N321001562-1.xls").getPath();
        String path = ThreeBomServiceImpl.class.getClassLoader().getResource(thempatePath).getPath();
        FileInputStream fis = new FileInputStream(path);
        return new HSSFWorkbook(fis);
    }

    //样式：单元格加边框，字体居中
    public HSSFCellStyle getBorderStyle(HSSFWorkbook h) {
        HSSFCellStyle style = h.createCellStyle();
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        style.setWrapText(true);//自动换行
        return style;
    }

    public void getPkOrgAanCode(String pkorg, String code) {
        if (this.pkorg == null) {
            this.pkorg = pkorg;
        }
        if (this.code == null) {
            this.code = code;
        }
    }
}
